#include "signal_manager.h"

#include <signal.h>
#include <assert.h>
#include <string.h>
#include <sys/socket.h>
#include <cerrno>

#include "global_env.h"

bool SignalManager::Init(){
    RegisterSig(SIGHUP);
    RegisterSig(SIGINT);
    RegisterSig(SIGPIPE);
    return true;
}


void SignalManager::RegisterSig(int sig, const SignalCallBack& signalCallBack) {
    struct sigaction sa;
    memset(&sa, '\0', sizeof(sa));

    sa.sa_handler = signalCallBack.target<void(int)>();
    sa.sa_flags |= SA_RESTART;
    sigfillset(&sa.sa_mask);

    assert(sigaction(sig, &sa, NULL) != -1);
}


void SignalManager::HandleSignals(){
    char signals[1024];
    int ret = recv(g_pipefd[0], signals, sizeof(signals), 0);
    if (ret == -1 || ret == 0) {
        return;
    } 
    for (int i = 0; i < ret; ++i) {
        switch (signals[i]) {
            case SIGINT: {
                g_stop_server = true;
                break;
            }
            case SIGHUP: {
                break;
            }
            case SIGPIPE: {
                //SIG_IGN(SIGPIPE); 
                break;
            }
        }
    }
}